import { defineStore } from 'pinia'
import type { UserLoginDTO } from '@/api/user'
import { userLogin } from '@/api/user'
import localCache from '@/utils/cache'
import { mapMenusToRoutes } from '@/utils/map-menu'

export const userLoginStore = defineStore('login', {
  state: () => ({
    username: '',
    avatar: '',
    token: '',
    menu: localCache.getCache('menu'),
  }),
  actions: {
    async setUserInfo(count: UserLoginDTO, isPasswordLogin: boolean) {
      const loginResult = await userLogin(count, isPasswordLogin) // 第二个参数表示是否密码登录
      this.username = loginResult.data.username
      this.avatar = loginResult.data.avatar
      this.token = loginResult.data.token

      console.log('username', this.username)
      // 保存到本地存储
      localCache.setCache('username', this.username)
      localCache.setCache('avatar', this.avatar)
      localCache.setCache('token', this.token)
      return loginResult
    },

    loadLocalCacheAction(router) {
      const username = localCache.getCache('username')
      const avatar = localCache.getCache('avatar')
      const token = localCache.getCache('token')
      const menu = localCache.getCache('menu')
      if (token && username && menu) {
        this.username = typeof username === 'string' ? username : ''
        this.avatar = typeof avatar === 'string' ? avatar : ''
        this.token = typeof token === 'string' ? token : ''
        this.menu = menu && Array.isArray(menu) ? menu : []
      }
      // 用户进行刷新默认加载数据
      const routes = mapMenusToRoutes(this.menu)
      routes.forEach((route) => router.addRoute('main', route))
    },
  },
})
